package com.paypalpay.controller.interfaces;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.paypalpay.entity.common.UnifiedOrderPackages;
import com.paypalpay.external.entity.ordernodevice.request.OrderList;
import com.paypalpay.external.entity.ordernodevice.request.RequestNoDeviceOrder;
import com.paypalpay.external.entity.ordernodevice.response.Data;
import com.paypalpay.external.entity.ordernodevice.response.ResponseNoDeviceOrder;
import com.paypalpay.external.entity.ordernodevice.response.TradeData;
import com.paypalpay.external.entity.userbound.response.UtilsInterfaces;
import com.paypalpay.external.utils.UtilsInterfacesPackage;
import com.paypalpay.service.InternationalPayPackageService;
import com.paypalpay.service.SequenceService;
import com.paypalpay.service.UnifiedOrderPackagesService;
import com.paypalpay.util.wx.MD5;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Demo 无卡下单控制类
 *
 * @author lm
 * @date 2018/08/31
 */
@RestController
@Api("前端无卡的微信用户下订单流程")
public class OrderNoDeviceController {
    @Autowired
    private HttpSession session;
    @Autowired
    private SequenceService sequenceService;

    @Autowired
    private InternationalPayPackageService internationalPayPackageService;

    @Autowired
    private UnifiedOrderPackagesService unifiedOrderPackagesService;

    private String token = "yv8JXeTTfqyedLcU2LAqHUTKtYA4G1kz";
    private String tradeType = "F0005";
    private String partnerCode = "00001";

    @CrossOrigin
    @RequestMapping(value = "/orderNoCard", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public String order(@RequestBody String requestStr) {
        System.out.println("请求报文是：" + requestStr);
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        // 1，生成流水号
        String ConnSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());

        RequestNoDeviceOrder orderNocard = JSONArray.parseObject(requestStr, RequestNoDeviceOrder.class);
        String requestSign = orderNocard.getSign();
        if (orderNocard.getSign() == null) {
            System.out.println("请求报文不合法:sign为空");
            String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
            return jsonString;
        } else {
            System.out.println("请求的sign是：" + requestSign);
            com.paypalpay.external.entity.ordernodevice.request.Data requestData = orderNocard.getData();
            if (orderNocard.getData() == null) {
                System.out.println("请求报文不合法:data为空");
                String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                return jsonString;
            } else {
                String partnerCode = requestData.getPartnerCode();
                String connSeqNo = requestData.getConnSeqNo();
                String token = requestData.getToken();
                String tradeTime = requestData.getTradeTime();
                String tradeType = requestData.getTradeType();
                if (requestData.getTradeData() == null) {
                    System.out.println("请求报文不合法:TradeData为空");
                    String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                    return jsonString;
                } else {
                    if (requestData.getTradeData().getIsOpen() == null || requestData.getTradeData().getOrderList() == null) {
                        System.out.println("请求报文不合法:TradeData内容为空");
                        String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                        return jsonString;
                    } else {
                            // 将请求体json转成String
                            String str = JSON.toJSONString(requestData);
                            // 将Str拿去计算签名
                            String sign = utils.calculateSignature(str);
                            System.out.println("计算的sign是：" + sign);
                            // 验证签名
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                // 签名不通过
                                String jsonString = utils.publicMessage(connSeqNo, tradeTime, partnerCode, token, tradeType);
                                return jsonString;

                            } else {
                                // 先把数据取出来
                                com.paypalpay.external.entity.ordernodevice.request.TradeData tradeData = requestData.getTradeData();
                                List<OrderList> orderList = tradeData.getOrderList();
                                List<TradeData> trade = new ArrayList<TradeData>();
                                TradeData tra = null;
                                String isOpen = tradeData.getIsOpen();
                                // 用序列生成一个temOrderId回回去
                                String temOrderId = sequenceService.getTemOrderId();
                                System.out.println("系统生成的temOrderId:" + temOrderId);
                                String channelOrderID = "";
                                for (OrderList order : orderList) {
                                    // 前端传过来的自动生成的id
                                    channelOrderID = order.getChannelOrderID();
                                    System.out.println("接收到的前端channelOrderId：" + channelOrderID);
                                    String orderUnit = order.getOrderUnit();
                                    String orderPeriod = order.getOrderPeriod();
                                    String packageCode = order.getPackageCode();
                                    String payAmount = order.getPayAmount();

                                    //根据前面得到的code去数据库查询name
                                    String packageName = internationalPayPackageService.getPackageNameBypackageCode(packageCode,partnerCode);
                                    System.out.println("套餐名称取到的是什么：" + packageName);

                                    UnifiedOrderPackages orders = new UnifiedOrderPackages();
                                    orders.setPackageName(packageName);
                                    orders.setPackageCode(packageCode);
                                    orders.setOrderPeriod(orderPeriod);
                                    orders.setOrderUnit(orderUnit);
                                    orders.setPayAmount(payAmount);
                                    orders.setIsOpen(isOpen);
                                    orders.setChannelOrderID(channelOrderID);
                                    orders.setCreateTime(tradeTime);
                                    //入库订购订单信息
                                    unifiedOrderPackagesService.putInOrderNoDeviceInfo(orders);

                                    System.out.println("到这里说明数据库入库操作完成：");


                                    if (channelOrderID != null || channelOrderID.length() > 0) {
                                        // 拼接返回的字符串儿
                                        tra = new TradeData();
                                        tra.setChannelOrderID(channelOrderID);
                                        tra.setTemOrderId(temOrderId);
                                        trade.add(tra);
                                    }
                                }
                                Data data = new Data();
                                data.setConnSeqNo(connSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setToken(token);
                                data.setTradeType(tradeType);
                                data.setTradeTime(curtime);
                                data.setTradeRstCode(1000);
                                data.setTradeRstMessage("success");
                                data.setTradeData(trade);

                                // 6，给ResponseOrder赋值
                                ResponseNoDeviceOrder responseorder = new ResponseNoDeviceOrder();
                                responseorder.setData(data);
                                System.out.println("签名体：" + JSON.toJSONString(data));
                                responseorder.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                // 返回给调用者的报文
                                String jsonString = JSON.toJSONString(responseorder);
                                System.out.println("回复的报文是：" + jsonString);
                                return jsonString;

                            }
                        }
                    }
                }
            }
        }
    }
